import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:s_mankey/config/net/smonkey_ui_api.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/config/router_config.dart';
import 'package:s_mankey/config/storage_manager.dart';
import 'package:s_mankey/model/user_model.dart';
import 'package:s_mankey/service/smonkey_repository.dart';
import 'package:s_mankey/ui/widget/custom_button.dart';
import 'package:s_mankey/ui/widget/show_toast.dart';
import 'package:s_mankey/view_model/login_vmodel.dart';
import 'package:shared_preferences/shared_preferences.dart';


class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPage createState() {
    return _LoginPage();
  }
}

class _LoginPage extends State<LoginPage> {

  TextEditingController _unameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();
  var list = ['86', '852', '853'];
  int areaIndex = 0;

  Map<String, dynamic> options = {}; //请求参数
//  VoidCallback successCallBack; //登录成功回调
//  VoidCallback failCallBack; //登录失败回调



  @override
  void initState() {
    print('进来了');
    options['area'] = list[areaIndex];
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  //登录请求
   login({Map<String, dynamic> options, VoidCallback successCallBack(var data), VoidCallback failCallBack(String msg)}) async {

    String url = 'https://api.in-monkeys.com/api/v1/login_password';
    Response response;
    Dio dio = Dio();
    response = await dio.post(url, data: options);
    Map<String, dynamic> data = response.data;

    if(data['code'] != 0) {
       return failCallBack(data['message']);
    }
    return successCallBack(data);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 1,
        title: Text('登录帐号'),
      ),
      body: Form(
        key: _formKey, //设置globalKey，用于后面获取FormState
        autovalidate: true, //开启自动校验
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: 40),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: GestureDetector(
                      onTap: () {
                        showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return new Column(
                                mainAxisSize: MainAxisSize.min,
                                children: List.generate(list.length, (index) {
                                  return new ListTile(
                                    leading: new Icon(Icons.phone),
                                    title: new Text(list[index]),
                                    onTap: () async {
                                      print('###${list[index]}');
                                      options['area'] = list[index];
                                      areaIndex = index;
                                      Navigator.pop(context);
                                      setState(() {

                                      });
                                    },
                                  );
                                }),
                              );
                            });
                      },
                      child: Row(
                        children: <Widget>[
                          Text('+'),
                          Text(list[areaIndex]),
                          Icon(
                            Icons.arrow_drop_down,
                          ),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 10),
                    width: 220,
                    child: TextFormField(
                        autofocus: true,
                        controller: _unameController,
                        decoration: InputDecoration(
//                    labelText: "手机号码",
                          hintText: "请输入手机号码",
                        ),
                        // 校验用户名
                        validator: (v) {
                          return v.trim().length > 0 ? null : "手机号码不能为空";
                        }),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: 280,
                    child: TextFormField(
                        controller: _pwdController,
                        decoration: InputDecoration(
                          labelText: "请输入密码",
                        ),
                        obscureText: true,
                        //校验密码
                        validator: (v) {
                          return v.trim().length > 5 ? null : "密码不能为空";
                        }
                        ),
                  ),

                ],
              ),
            ),

            /// 点击绑定
            GestureDetector(
              onTap: ()  {
                options['mobile'] = _unameController.text;
                options['password'] = _pwdController.text;
                print('点击登录了${options}');
                login(options: options,
                    failCallBack: (msg){
                  Toast.toast(context,msg: msg);
                  return;
                },
                    successCallBack: (data){
                  UserModel userModel = UserModel.fromJson(data['data']); //数据转模型
                  http.options.headers = {'token': userModel.accessToken}; //添加请求参数
                  var model = Provider.of<LoginVModel>(context,listen: false);
                  model.saveUser(userModel); //保存到全局数据
                  Toast.toast(context,msg: data['message']);
                  Navigator.pushNamed(context, RouterName.tabNav);
                    return;
                });

              },
              child: CustomButton(
                  margin: EdgeInsets.only(top: 20),
                  padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                  widgt: 250.0,
                  title: '登录',
                  fontSize: AppFontSize.Size18,
                  fontColor: Colors.white,
                  radius: 30.0,
                  borderColor: Colors.transparent,
                  gradient: AppColor.gradientColorHigh),
            ),
          ],
        ),
      ),
    );
  }
}
